package com.mzba.easy.weibo.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.ui.GridViewAdapter;
import com.mzba.easy.weibo.ui.UserinfoActivity;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
/**
 * 
 * @author 06peng
 *
 */
public class CommentView extends LinearLayout implements Callback, BasicUIEvent {

	private Context context;
	private CommentEntry entry;
	private WeiboManager weiboManager;
	private Handler handler;
	private boolean isRetweet = false;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int reply_comment = 0x00000102;
	private static final int reply_comment_error = 0x00000103;
	
	private View itemView;
	private View commentItem;
	private LinearLayout preView;
	public CustomDialog dialog;
	public IPhoneDialog.Builder alert = null;
	public boolean alertIsShow = false;
	
	ImageButton emotionView;
	ImageView retweetView;
	LinearLayout retweetSelectLayout;
	Button commentView;
	EditText editView;
	LinearLayout bodyLayout;
	
	RemoteImageView avatarView;
	CustomTextView textView;
	TextView replyView;
	
	private PopupWindow pop;
	private LayoutParams paramsTop;

	public CommentView(Context context, CommentEntry entry) {
		super(context);
		this.context = context;
		this.entry = entry;
		weiboManager = new WeiboManager(context);
		handler = new Handler(this);
		this.setOrientation(LinearLayout.VERTICAL);
		try {
			initWidget();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.addView(itemView);
		
		paramsTop = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		paramsTop.topMargin = 5;
		
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					editView.append(filed.getPhrase());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public CommentView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CommentView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	private void initWidget() throws Exception {
		itemView = LayoutInflater.from(context).inflate(R.layout.comment_body_item, null);
		avatarView = (RemoteImageView) itemView.findViewById(R.id.iv_author_photo);
		replyView = (TextView) itemView.findViewById(R.id.comment_body_reply);
		textView = (CustomTextView) itemView.findViewById(R.id.comment_body_text);
		avatarView.setDefaultImage(R.drawable.avatar_default_big);
		avatarView.setImageUrl(entry.getUser().getProfile_image_url());
		String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
		textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
//		bodyLayout.addView(itemView, paramsTop);
//		ImageView imageLine = new ImageView(context);
//		imageLine.setBackgroundResource(R.drawable.divider_horizontal_timeline);
//		bodyLayout.addView(imageLine, paramsTop);
		
		avatarView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, UserinfoActivity.class);
				intent.putExtra("userid", entry.getUser().getId());
				context.startActivity(intent);
			}
		});
		replyView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if (preView == null) {
					createCommentItemView();
					CommentView.this.addView(commentItem);
				} else {
					if (preView == CommentView.this) {
						if (commentItem.isShown()) {
							CommentView.this.removeView(commentItem);
						} else {
							CommentView.this.addView(commentItem);
						}
					} else {
						preView.removeView(commentItem);
						CommentView.this.addView(commentItem);
					}
				}
				preView = CommentView.this;
				
				editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
				editView.setFocusable(true);
				editView.setFocusableInTouchMode(true);
			}
		});
	}
	
	private void createCommentItemView() {
		commentItem = LayoutInflater.from(context).inflate(R.layout.timeline_comment_item, null);
		editView = (EditText) commentItem.findViewById(R.id.timeline_comment_edit);
		emotionView = (ImageButton) commentItem.findViewById(R.id.timeline_comment_emotion);
		retweetView = (ImageView) commentItem.findViewById(R.id.timeline_comment_retweet_select);
		retweetSelectLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_retweet_select_layout);
		commentView = (Button) commentItem.findViewById(R.id.timeline_comment_comment);
		bodyLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_body_layout);
		
		commentView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loading();
				String content = editView.getText().toString().trim();
				Object[] objs = new Object[4];
				objs[0] = content;
				objs[1] = entry.getStatus().getId();
				objs[2] = entry.getId();
				objs[3] = isRetweet == true ? 1 : 0;
				UICore.eventTask(CommentView.this, (BasicActivity) context, reply_comment, "", objs); 
			}
		});
		
		emotionView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!pop.isShowing()) {
					pop.showAtLocation(commentItem, Gravity.BOTTOM, 0, 0);
				} else {
					pop.dismiss();
				}
			}
		});
		
		retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isRetweet) {
					isRetweet = false;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
				} else {
					isRetweet = true;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
				}
			}
		});
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case reply_comment:
			destroyDialog();
			onToast("评论成功");
			break;
		case reply_comment_error:
			destroyDialog();
			onToast("评论失败");
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case reply_comment:
			Object[] objs2 = (Object[]) obj;
			CommentEntry commentEntry2 = weiboManager.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
					Integer.parseInt(objs2[3].toString()));
			if (commentEntry2 != null) {
				handler.sendEmptyMessage(reply_comment);
			} else {
				handler.sendEmptyMessage(reply_comment_error);
			}
			break;

		default:
			break;
		}
	}
	
	public void loading() {
		try {
			if (dialog == null || !dialog.isShowing()) {
				View progressview = LayoutInflater.from(context).inflate(R.layout.progress_dialog, null);
				CustomDialog.Builder progressBuilder = new CustomDialog.Builder(context);
				progressBuilder.setContentView(progressview);
				dialog = progressBuilder.create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroyDialog() {
		handler.sendEmptyMessage(DESTROYDIALOG);
	}
	
	public void onToast(String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}
}
